/*
 * @Description:人员列表 组件提取
 * @Date: 2022-06-10 14:01:42
 * @LastEditTime: 2022-06-10 14:15:49
 */
import React, { useEffect, useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { history, useRequest } from 'umi';

export default (props: any) => {
  const [proTableData, setProTableData] = useState([]);
  const addPersonFrom = useRef<ProFormInstance>();
  const [filedDisable, setFiledDisable] = useState({
    username: true,
    technicalGrade: true,
    technicalName: true,
    type: true,
  });

  const columns: any = [
    {
      title: '工号',
      key: 'username',
      dataIndex: 'username',
    },
    {
      title: '姓名',
      key: 'realName',
      dataIndex: 'realName',
    },
    {
      title: '排名',
      dataIndex: 'userRank',
      key: 'userRank',
      valueType: 'digit',
    },
    {
      title: '身份',
      key: 'userIdentify',
      dataIndex: 'userIdentify',
    },
    {
      title: '职称等级',
      key: 'technicalGrade',
      dataIndex: 'technicalGrade',
    },
    {
      title: '职称名称',
      key: 'technicalName',
      dataIndex: 'technicalName',
    },
    {
      title: '人员类别',
      key: 'userType',
      dataIndex: 'userType',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {

            const newtabledata = proTableData.filter(
              (item: any) => item.username !== record.username,
            );
            // console.log(newtabledata);
            setProTableData(newtabledata);
            props?.getTableData(newtabledata); //table数据回传父组件
            message.info('临时删除人员，确认人员名单后请提交！');
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  //根据职称等级选择职称名称
  const getLike = useRequest(
    (data = { field: 'technicalName', level: '正高级' }) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      // manual: true,
    },
  );
  //根据名字查找人详细信息
  const findOneUserInfoDetailByName = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/user/findOneUserInfoDetailByName',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  const nameOnSearch = () => {
    findOneUserInfoDetailByName
      .run({ realName: addPersonFrom.current?.getFieldValue('realName') })
      .then((e) => {
        if (e !== null && e.length !== 0) {
          let filedDisableTemp: any = JSON.parse(JSON.stringify(filedDisable));
          Object.keys(e[0]).map((key: any) => {
            if (e[0][key] === null) {
              filedDisableTemp[`${key}`] = false;
            } else {
              filedDisableTemp[`${key}`] = true;
            }
          });
          setFiledDisable(filedDisableTemp);
          addPersonFrom.current?.setFieldsValue(e[0]);
        } else {
          setFiledDisable({
            username: false,
            technicalGrade: false,
            technicalName: false,
            type: false,
          });
          addPersonFrom.current?.resetFields();
          message.info('暂无此用户，自行填写信息');
        }
      });
  };
  const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  useEffect(() => {
    setProTableData(props?.personData);
    props?.getTableData(props?.personData); //table数据回传父组件
  }, [props?.personData]);

  return (
    <ProCard
      bordered
      title={'人员信息'}
      extra={
        <Space>
          <ModalForm<{
            name: string;
            company: string;
          }>
            title="添加人员"
            trigger={
              <Button
                key="button"
                size="small"
                icon={<PlusOutlined />}
                type="primary"
              >
                新增人员
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => {
                setFiledDisable({
                  username: true,
                  technicalGrade: true,
                  technicalName: true,
                  type: true,
                });
                addPersonFrom.current?.resetFields();
              },
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              await waitTime(1000);
              let proTableDataTemp: any = JSON.parse(
                JSON.stringify(proTableData),
              );
              proTableDataTemp.push(values);
              setProTableData(proTableDataTemp);
              props?.getTableData(proTableDataTemp); //table数据回传父组件
              message.success('临时添加人员，确认人员名单后请提交！');
              return true;
            }}
            formRef={addPersonFrom}
          >
            <ProForm.Group>
              <ProFormText
                width="md"
                name="realName"
                required
                label="人员名称"
                addonAfter={[
                  <Button type="primary" key={'search'} onClick={nameOnSearch}>
                    检索用户
                  </Button>,
                ]}
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText
                width="xs"
                name="username"
                label="人员工号"
                disabled={filedDisable.username}
                required
              />
              <ProFormSelect
                request={async () => [
                  {
                    value: '正高级',
                    label: '正高级',
                  },
                  {
                    value: '副高级',
                    label: '副高级',
                  },
                  {
                    value: '中级',
                    label: '中级',
                  },
                  {
                    value: '初级',
                    label: '初级',
                  },
                ]}
                width="xs"
                name="technicalGrade"
                label="职称等级"
                disabled={filedDisable?.technicalGrade}
                required
                fieldProps={{
                  onChange: (e) => {
                    getLike.run({ field: 'technicalName', level: e });
                    addPersonFrom.current?.setFieldsValue({
                      technicalName: null,
                    });
                  },
                }}
              />
              <ProFormSelect
                width="sm"
                name="technicalName"
                label="人员职称"
                disabled={filedDisable.technicalName}
                required
                fieldProps={{
                  options: getLike.data,
                }}
              />
              <ProFormSelect
                request={async () => [
                  {
                    value: '固定人员',
                    label: '固定人员',
                  },
                  {
                    value: '流动人员',
                    label: '流动人员',
                  },
                  {
                    value: '学生',
                    label: '学生',
                  },
                  {
                    value: '非本室人员',
                    label: '非本室人员',
                  },
                ]}
                width="sm"
                name="userType"
                label="人员类别"
                disabled={filedDisable.type}
                required
              />
            </ProForm.Group>

            <ProForm.Group>
              <ProFormDigit
                width="xs"
                label="人员排名"
                name="userRank"
                min={1}
                max={10}
                fieldProps={{ precision: 0 }}
                required
              />
              <ProFormSelect
                request={async () => [
                  {
                    value: '独立完成',
                    label: '独立完成',
                  },
                  {
                    value: '第一完成人(非独立完成)',
                    label: '第一完成人(非独立完成)',
                  },
                  {
                    value: '非第一完成人(非独立完成)',
                    label: '非第一完成人(非独立完成)',
                  },
                ]}
                width="sm"
                name="completeState"
                label="完成情况"
                required
              />
              <ProFormSelect
                request={async () => [
                  {
                    value: '第一作者',
                    label: '第一作者',
                  },
                  {
                    value: '通讯作者',
                    label: '通讯作者',
                  },
                  {
                    value: '其他',
                    label: '其他',
                  },
                ]}
                width="md"
                name="userIdentify"
                label="人员身份"
                required
              />
            </ProForm.Group>
          </ModalForm>
        </Space>
      }
    >
      <ProTable
        rowKey={'username'}
        columns={columns}
        search={false}
        dataSource={proTableData}
        toolBarRender={false}
      />
    </ProCard>
  );
};
